﻿using Newtonsoft.Json;
using RTW.OA.Areas.Common.Servers;
using RTW.OA.Areas.System.Servers;
using RTW.OA.Attributes;
using RTW.OA.Controllers;
using RTW.OA.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;

namespace RTW.OA.Areas.Document.Controllers
{
    [CheckLogin(IsChildPage = true)]
    public class SendController : BaseController
    {
        private DocumentServers documentServers;
        private DocumentReceiveServers documentReceiveServers;
        private UserServers userServers;
        private PositionServers positionServers;

        public SendController()
        {
            documentServers = new DocumentServers();
            documentReceiveServers = new DocumentReceiveServers();
            userServers = new UserServers();
            positionServers = new PositionServers();
        }

        [HttpGet]
        public ActionResult Index(string SUBJECT, string DOC_NUM, string M_START, string M_END)
        {
            var datalist = documentServers.GetData(this.CurrentUser.USER_NO, SUBJECT, DOC_NUM, M_START, M_END);
            foreach (var item in datalist)
            {
                item.official_document_receives = documentReceiveServers.GetData(item.DOC_ID);
            }
            return View(datalist);
        }

        public string GetDataTableJsonResult(string SUBJECT, string DOC_NUM, string M_START, string M_END)
        {
            var datalist = documentServers.GetData(this.CurrentUser.USER_NO, SUBJECT, DOC_NUM, M_START, M_END);
            return JsonConvert.SerializeObject(datalist);
            //return Json(datalist,JsonRequestBehavior.AllowGet);
        }

        private IEnumerable<SelectListItem> GetSelectList(string[] options, string defaultValue = null)
        {
            var list = new List<SelectListItem>();
            foreach (var item in options)
            {
                var selectListItem = new SelectListItem
                {
                    Text = item,
                    Value = item,
                    Selected = (defaultValue != null ? item == defaultValue : false)
                };
                list.Add(selectListItem);
            }
            return list;
        }

        public void SaveDoc(string filePath)
        {
            PageOffice.FileSaver fs = new PageOffice.FileSaver();
            fs.SaveToFile(Server.MapPath(filePath));
            fs.Close();
        }

        public ActionResult OfficeView(string filePath)
        {
            string suffix = Path.GetExtension(filePath);

            PageOffice.PageOfficeCtrl pc = new PageOffice.PageOfficeCtrl();
            pc.AddCustomToolButton("保存", "Save()", 1);
            pc.AddCustomToolButton("打印", "ShowPrintDlg()", 6);
            pc.AddCustomToolButton("-", "", 0);
            pc.AddCustomToolButton("全屏切换", "SwitchFullScreen()", 4);
            pc.SaveFilePage = "/Document/Send/SaveDoc?filePath="+ Url.Encode(filePath);
            pc.ServerPage = "/PageOffice/server.aspx";
            switch (suffix.ToLower())
            {
                case ".doc":
                case ".docx":
                    pc.WebOpen(filePath, PageOffice.OpenModeType.docReadOnly, "s");
                    break;
                case ".xls":
                case ".xlsx":
                    pc.WebOpen(filePath, PageOffice.OpenModeType.xlsReadOnly, "s");
                    break;
                default:
                    break;
            }
            ViewBag.ContentHtml = pc.GetHtmlCode("PageOfficeCtrl1");

            return View();
        }

        // GET: Document/Send/Details/5
        public ActionResult Details(int id)
        {
            var model = documentServers.GetModelById(id);

            return View(model);
        }

        // GET: Document/Send/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Document/Send/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Document/Send/Edit/5
        public ActionResult Edit(int? id)
        {
            ViewBag.TEMPLATE_LIST = this.GetSelectList(new string[] { "本地模板" });
            string[] URGENT_LEVEL_LIST = { "普通", "平急", "加急", "特急", "特提" };
            string[] SECRET_LEVEL_LIST = { "非密", "秘密", "机密", "绝密" };
            string[] DOC_CATEGORY_LIST = { "要求", "通知", "公文", "文件" };
            if (id.HasValue)
            {
                ViewBag.Title = "编辑发文";
                var model = documentServers.GetModelById(id.Value);
                ViewBag.URGENT_LEVEL_LIST = this.GetSelectList(URGENT_LEVEL_LIST, model.URGENT_LEVEL);
                ViewBag.SECRET_LEVEL_LIST = this.GetSelectList(SECRET_LEVEL_LIST, model.SECRET_LEVEL);
                ViewBag.DOC_CATEGORY_LIST = this.GetSelectList(DOC_CATEGORY_LIST, model.DOC_CATEGORY);
                return View(model);
            }
            else
            {
                ViewBag.URGENT_LEVEL_LIST = this.GetSelectList(URGENT_LEVEL_LIST);
                ViewBag.SECRET_LEVEL_LIST = this.GetSelectList(SECRET_LEVEL_LIST);
                ViewBag.DOC_CATEGORY_LIST = this.GetSelectList(DOC_CATEGORY_LIST);
                ViewBag.Title = "新建发文";
                return View();
            }
        }

        // POST: Document/Send/Edit/5
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(official_document model)
        {
            try
            {
                if (model.DOC_ID == 0)
                {
                    var leaderInfo = userServers.GetLeaderByUserNO(this.CurrentUser.USER_NO);
                    model.DRAFT_USER_NO = this.CurrentUser.USER_NO;
                    model.CREATE_TIME = DateTime.Now;
                    model.DEPT_LEADER = leaderInfo.TRUE_NAME;
                    model.DEPT_LEADER_USER_NO = leaderInfo.USER_NO;
                    model.IS_ARCHIVE = false;

                    documentServers.Add(model);
                    ViewBag.msg = "新建发文保存成功！";
                    model = new official_document();

                }
                else
                {
                    model.CREATE_TIME = DateTime.Now;
                    model.SIGNATURE_TIME = null;
                    model.STATUS = 0;
                    model.IS_ARCHIVE = false;
                    documentServers.Update(model);
                    ViewBag.msg = "发文修改成功！";
                }
            }
            catch
            {
                ViewBag.msg = "提交出现错误！";
            }
            return RedirectToAction("index");
        }

        [HttpPost]
        public JsonResult SendDocument(int id)
        {
            try
            {
                var model = documentServers.GetModelById(id);
                List<string> userlist = new List<string>();
                if (!string.IsNullOrEmpty(model.RECEIVERS))
                {
                    var receiveUsers = model.RECEIVERS.Split(',');
                    var receiveUserNames = model.RECEIVERS_TEXT.Split(',');
                    for (int i = 0; i < receiveUsers.Length; i++)
                    {
                        var item = receiveUsers[i];
                        if (item.Length > 1)
                        {
                            var receiveUserId = item.Substring(1);
                            var documentReceive = new official_document_receive
                            {
                                RECEIVER_USER_NO = userServers.GetUserNO(receiveUserId),
                                RECEIVER_NAME = receiveUserNames[i],
                                RECEIVE_UNIT = model.RECEIVE_UNITS_TEXT,
                                CREATE_TIME = DateTime.Now,
                                STATUS = 0,
                                REG_ID = Guid.NewGuid().ToString("N"),
                                DOC_ID = model.DOC_ID
                            };
                            userlist.Add(documentReceive.RECEIVER_USER_NO);
                            documentReceiveServers.Add(documentReceive);
                        }
                    }
                }
                return Json(new
                {
                    code = 100,
                    data = userlist,
                    msg = "更新成功"
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new
                {
                    code = 0,
                    msg = "更新失败，原因：" + e.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpGet]
        public ActionResult Approval(int id)
        {
            ViewBag.TEMPLATE_LIST = this.GetSelectList(new string[] { "本地模板" });
            string[] URGENT_LEVEL_LIST = { "普通", "平急", "加急", "特急", "特提" };
            string[] SECRET_LEVEL_LIST = { "非密", "秘密", "机密", "绝密" };
            string[] DOC_CATEGORY_LIST = { "要求", "通知", "公文", "文件" };
            ViewBag.Title = "编辑发文";
            var model = documentServers.GetModelById(id);
            ViewBag.URGENT_LEVEL_LIST = this.GetSelectList(URGENT_LEVEL_LIST, model.URGENT_LEVEL);
            ViewBag.SECRET_LEVEL_LIST = this.GetSelectList(SECRET_LEVEL_LIST, model.SECRET_LEVEL);
            ViewBag.DOC_CATEGORY_LIST = this.GetSelectList(DOC_CATEGORY_LIST, model.DOC_CATEGORY);
            return View(model);
        }

        public JsonResult SetApproval(int id, int status, string remark = null)
        {
            try
            {
                documentServers.UpdateStatus(id, status, remark);
                return Json(new
                {
                    code = 100,
                    msg = "更新成功"
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new
                {
                    code = 0,
                    msg = "更新失败，原因：" + e.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }


        [HttpGet]
        public ActionResult SetDocNumber(int id)
        {
            var model = documentServers.GetModelById(id);
            string[] DOC_YEAR_LIST = { "2019年", "2018年" };
            string[] URGENT_LEVEL_LIST = { "普通", "平急", "加急", "特急", "特提" };
            string[] SECRET_LEVEL_LIST = { "非密", "秘密", "机密", "绝密" };
            string[] CATEGORY_LIST = { "鄂检", "鄂执" };
            string[] DOC_CATEGORY_LIST = { "要求", "通知", "公文", "文件" };

            ViewBag.DOC_YEAR_LIST = this.GetSelectList(DOC_YEAR_LIST, model.DOC_YEAR);
            ViewBag.SECRET_LEVEL_LIST = this.GetSelectList(SECRET_LEVEL_LIST, model.SECRET_LEVEL);
            ViewBag.URGENT_LEVEL_LIST = this.GetSelectList(URGENT_LEVEL_LIST, model.URGENT_LEVEL);
            ViewBag.CATEGORY_LIST = this.GetSelectList(CATEGORY_LIST, model.CATEGORY);
            ViewBag.DOC_CATEGORY_LIST = this.GetSelectList(DOC_CATEGORY_LIST, model.DOC_CATEGORY);
            return View(model);
        }

        [ValidateInput(false)]
        public ActionResult SetDocNumber(official_document model)
        {
            //var model = documentServers.GetModelById(id);
            model.STATUS = 5;
            model.SIGNER_USER_NO = this.CurrentUser.USER_NO;
            model.SIGNATURE_TIME = DateTime.Now;
            if (model.CREATE_TIME.HasValue)
            {
                model.CREATE_TIME = Convert.ToDateTime(model.CREATE_TIME);
            }
            documentServers.Update(model);

            string[] DOC_YEAR_LIST = { "2019年", "2018年" };
            string[] URGENT_LEVEL_LIST = { "普通", "平急", "加急", "特急", "特提" };
            string[] SECRET_LEVEL_LIST = { "非密", "秘密", "机密", "绝密" };
            string[] CATEGORY_LIST = { "鄂检", "鄂执" };
            string[] DOC_CATEGORY_LIST = { "要求", "通知", "公文", "文件" };

            ViewBag.DOC_YEAR_LIST = this.GetSelectList(DOC_YEAR_LIST, model.DOC_YEAR);
            ViewBag.SECRET_LEVEL_LIST = this.GetSelectList(SECRET_LEVEL_LIST, model.SECRET_LEVEL);
            ViewBag.URGENT_LEVEL_LIST = this.GetSelectList(URGENT_LEVEL_LIST, model.URGENT_LEVEL);
            ViewBag.CATEGORY_LIST = this.GetSelectList(CATEGORY_LIST, model.CATEGORY);
            ViewBag.DOC_CATEGORY_LIST = this.GetSelectList(DOC_CATEGORY_LIST, model.DOC_CATEGORY);
            return View(model);
        }

        [HttpPost]
        public JsonResult SetSigner(int id, string signerId, string signerName)
        {
            try
            {
                if (!string.IsNullOrEmpty(signerId) && signerId.Contains("U"))
                {
                    signerId = signerId.Substring(1);
                    var model = userServers.GetModelById(signerId);
                    documentServers.UpdateSigner(id, model.USER_NO, signerName);
                    return Json(new
                    {
                        code = 100,
                        msg = "更新成功"
                    }, JsonRequestBehavior.AllowGet);
                }
                return Json(new
                {
                    code = 0,
                    msg = "更新失败",
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new
                {
                    code = 0,
                    msg = "更新失败，原因：" + e.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult RequestNextStep(int id)
        {
            try
            {
                var model = documentServers.GetModelById(id);
                model.STATUS++;
                //int newStatus = model.STATUS + 1;
                documentServers.UpdateStatus(id, model.STATUS);
                return Json(new
                {
                    code = 100,
                    data = model,
                    msg = "更新成功"
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new
                {
                    code = 0,
                    msg = "更新失败，原因：" + e.Message
                }, JsonRequestBehavior.AllowGet);
            }

        }

        public ActionResult SelectReceiver(string id)
        {
            ViewBag.right = id ?? "";
            return View();
        }

        public ActionResult SelectDocNumberUser(int id, int status)
        {
            ViewBag.DocId = id;
            ViewBag.DocStatus = status;
            return View();
        }


        public ActionResult GetjsonTreeData(string idstr = null)
        {
            var list = GetDepts(0, idstr);
            return Json(list, JsonRequestBehavior.AllowGet);
        }


        public List<TreeViewNode> GetDepts(int parentId, string idstr)
        {
            List<TreeViewNode> tlist = new List<TreeViewNode>();
            var list = positionServers.GetDepts();
            var deptlist = list.FindAll(m => m.DEPT_PARENT == parentId);
            if (deptlist != null && deptlist.Count > 0)
            {
                foreach (var item in deptlist)
                {
                    TreeViewNode treeViewNode = new TreeViewNode
                    {
                        text = item.DEPT_NAME,
                        id = "D" + item.DEPT_ID.ToString(),
                        icon = "glyphicon glyphicon-equalizer",
                        nodes = new List<TreeViewNode>()
                    };
                    var personlist = GetPerson(item.DEPT_ID, idstr);
                    if (personlist != null && personlist.Count > 0)
                    {
                        treeViewNode.nodes.AddRange(personlist);
                    }
                    var subdeptlist = GetDepts(item.DEPT_ID, idstr);
                    if (subdeptlist != null && subdeptlist.Count > 0)
                    {
                        treeViewNode.nodes.AddRange(subdeptlist);
                    }
                    if (!string.IsNullOrEmpty(idstr))
                    {
                        if (idstr.Contains("D" + item.DEPT_ID.ToString()))
                        {
                            treeViewNode.state = new State { @checked = true };
                        }

                    }

                    tlist.Add(treeViewNode);
                }
            }
            return tlist;

        }

        public List<TreeViewNode> GetPerson(int parentId, string idstr)
        {
            List<TreeViewNode> tlist = new List<TreeViewNode>();
            var list = positionServers.GetUsers().FindAll(m => m.DEPT_ID == parentId);
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    TreeViewNode treeViewNode = new TreeViewNode
                    {
                        text = item.TRUE_NAME,
                        id = "U" + item.USER_ID.ToString(),
                        icon = "glyphicon glyphicon-user"
                    };
                    if (!string.IsNullOrEmpty(idstr))
                    {
                        if (idstr.Contains("U" + item.DEPT_ID.ToString()))
                        {
                            treeViewNode.state = new State { @checked = true };
                        }

                    }
                    tlist.Add(treeViewNode);
                }
            }
            return tlist;
        }

        [HttpPost]
        public JsonResult DocumentDelete(string id)
        {
            try
            {
                //documentServers.Del(id);
                return Json(new
                {
                    code = 100,
                    msg = "删除成功"
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new
                {
                    code = 0,
                    msg = "删除失败，原因：" + e.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        // POST: Document/Send/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
